using System;
using UnityEngine;

public class MobileJoystick : MonoBehaviour
{

    [Header("Elements")] 
    [SerializeField] private RectTransform joystickOutline;
    [SerializeField] private RectTransform joystickKnob;

    [Header("Settings")]
    [SerializeField] private float moveFactor;
    private Vector3 clickedPosition;
    private bool canControl;
    private Vector3 move;

    private void Start()
    {
        HideJoystick();
    }

    private void Update()
    {
        if (canControl)
        {
            ControlJoystick();
        }
    }

    public void ClickedOnJoystickZoneCallback()
    {
        clickedPosition = Input.mousePosition;
        joystickOutline.position = clickedPosition;

        
        ShowJoystick();
    }


    // 显示摇杆
    private void ShowJoystick()
    {
        canControl = true;
        joystickOutline.gameObject.SetActive(true);
    }

    // 隐藏摇杆
    private void HideJoystick()
    {
        canControl = false;
        move = Vector3.zero;
        joystickOutline.gameObject.SetActive(false);
    }

    private void ControlJoystick()
    {
        var currentPosition = Input.mousePosition;
        var direction = currentPosition - clickedPosition;

        // 计算移动幅度
        float moveMagnitude = direction.magnitude * moveFactor / Screen.width;
        moveMagnitude = Mathf.Min(moveMagnitude, joystickOutline.rect.width / 2);

        move = direction.normalized * moveMagnitude;
        var targetPosition = clickedPosition + move;
        joystickKnob.position = targetPosition;

        if (Input.GetMouseButtonUp(0))
        {
            HideJoystick();
        }
    }

    public Vector3 GetMoveVector()
    {
        return new Vector3(move.x, 0, move.y);
    }
}
